<?php

namespace app\admin\controller\pifa;

use app\common\controller\Backend;

use addons\epay\library\Service;
use Yansongda\Pay\Pay;
use think\Log;
use fast\Huipay;
use think\Db;
use addons\faqueue\library\QueueApi;
use think\Collection;
/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\pifa\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pifa\Order;
        $this->view->assign("orderstateList", $this->model->getOrderstateList());
        $this->view->assign("fenstateList", $this->model->getFenstateList());
        $this->view->assign("shippingstateList", $this->model->getShippingstateList());
        $this->view->assign("paystateList", $this->model->getPaystateList());
         $this->view->assign("tuikuanList", $this->model->getTuikuanList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */




    // 第一个页面：筛选条件页
    public function gysexport()
    {   

        if ($this->request->isAjax()) {


           $this->success();
        }


        // 只是显示筛选页
        return $this->view->fetch();
    }

    // 第二个页面：展示结果页
    public function gysexportpage()
    {   

        $post = $this->request->request();



        $map['createday'] = ['between',[$post['start'],$post['end']]];
        // $map['paystate'] = '1';
        // $map['orderstate'] = ['not in',[0,3,4]];
        $order_ids = Db::table('fa_pifa_order')->where($map)->column('id');
        $Orderitem = new \app\admin\model\pifa\Orderitem;
        $map2['order_id'] = ['in',$order_ids];
        $order_item_list = $Orderitem->where($map2)->select();

        $gys_listv = Db::table('fa_pifa_gongyingshang')->cache(true)->column('*','id');
        
        if ($order_item_list instanceof \think\Collection) {
            $list = $order_item_list->toArray();
        } else {
            $list = $order_item_list;
        }
        $grouped = [];

        foreach ($list as $item) {
            // 供应商 ID
            $supplier_id = !empty($item['gongyingshang_id']) ? $item['gongyingshang_id'] : 0;

            // 单品唯一ID（优先 goodsitem.id，没有就用 goods_id）
            $goods_id = $item['goods_id'] ?? 0;
            $goodsitem_id = $item['goodsitem']['id'] ?? ($item['goods_item_id'] ?? 0);
            $sku_key = $goodsitem_id ? "gitem_{$goodsitem_id}" : "goods_{$goods_id}";

            // 初始化供应商分组
            if (!isset($grouped[$supplier_id])) {
                $grouped[$supplier_id] = [
                    'gongyingshang' => $gys_listv[$supplier_id] ?? [],
                    'goods' => [],
                ];
            }

            // 初始化该单品
            if (!isset($grouped[$supplier_id]['goods'][$sku_key])) {
                $grouped[$supplier_id]['goods'][$sku_key] = [
                    'goods_id'     => $goods_id,
                    'goodsitem_id' => $goodsitem_id,
                    'goods_name'   => $item['goods_name'] . $item['name'],
                    'total_num'    => 0,
                    // 'items'        => [],  // 保存明细，可选
                ];
            }

            // 累加数量
            $grouped[$supplier_id]['goods'][$sku_key]['total_num'] += $item['goods_num'] ?? 0;

            // 可选：保留原始明细行
            // $grouped[$supplier_id]['goods'][$sku_key]['items'][] = $item;
        }

        // ✅ 结果：$grouped 的结构清晰且可直接导出
        // foreach ($grouped as $supplier_id => $data) {
        //     $gys_name = $data['gongyingshang']['name'] ?? '未设置供应商';
        //     echo "供应商：{$gys_name}（ID: {$supplier_id}）\n";

        //     foreach ($data['goods'] as $sku_key => $goods_data) {
        //         echo "  单品 {$goods_data['goods_name']} 数量：{$goods_data['total_num']}\n";
        //     }
        // }

        // 如果要导出表格时使用，可以直接拉平
        $flat_items = [];
        foreach ($grouped as $supplier_id => $data) {
            foreach ($data['goods'] as $goods) {
                $flat_items[] = [
                    'supplier_id' => $supplier_id,
                    'supplier_name' => $data['gongyingshang']['name'] ?? '',
                    'goods_id' => $goods['goods_id'],
                    'goodsitem_id' => $goods['goodsitem_id'],
                    'goods_name' => $goods['goods_name'],
                    'total_num' => $goods['total_num'],
                ];
            }
        }

        $this->view->assign('post', $post);
        $this->view->assign('grouped', $grouped);
        return $this->view->fetch();    

    }




    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','inv','mendian','address'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname','mobile','avatar']);
                $row->getRelation('inv')->visible(['nickname','mobile','avatar']);
            }
            
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


     public function detail($ids = null){
        // if($this->request->isPost())
        // {
        //     $id = input('post.ids');
        //     $row = $this->model->get($id);
        //     $params = $this->request->post('row/a');
        //     $row['peisong_user_id'] = $params['peisong_user_id'];

           
        //     $row->save();
        //     $this->success();
        // }

        //  if($this->request->isPost())
        // {
        //     $id = input('post.ids');
        //     $row = $this->model->get($id);
        //     $row['freight_status'] = "1";
        //     $row['orderstate'] = 2;
        //     $row['freight_time'] = time();
        //     $row['express_company'] = input('post.express_company');
        //     $row['express_no'] = input('post.express_no');
        //     $row->save();
        //     $this->success();
        // }
        if($this->request->isPost())
        {
            $id = input('post.ids');
            $row = $this->model->get($id);
            $params = $this->request->post('row/a');
            $row['peisong_user_id'] = $params['peisong_user_id'];

           
            $row->save();
            $this->success();
        }

        $param = $this->request->param();
        // $row = $this->model->get($ids);
        $row = $this->model->with(['peisong','mendian'])->find($ids);
        // var_dump($row->toArray()['peisong']);
        $this->view->assign('vo', $row);
        $this->view->assign('peisong', $row->toArray()['peisong']);

        $map['order_id'] = $ids;
        $peisong_desc = Db::table('fa_pifa_orderdesc')->where($map)->select();


        foreach ($peisong_desc as $key => $value) {
           $value['images'] = explode(',',$value['images']);

           foreach ($value['images'] as $key1 => $value1) {
               $value['images'][$key1] = $value1;
           }

           $peisong_desc[$key]['images'] = $value['images'];

           
           $peisong_desc[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
        }


        
        $this->view->assign('peisong_desc', $peisong_desc);

        return $this->view->fetch();
    }


    public function paidan($ids = null){
        // if($this->request->isPost())
        // {
        //     $id = input('post.ids');
        //     $row = $this->model->get($id);
        //     $params = $this->request->post('row/a');
        //     $row['peisong_user_id'] = $params['peisong_user_id'];

           
        //     $row->save();
        //     $this->success();
        // }

        //  if($this->request->isPost())
        // {
        //     $id = input('post.ids');
        //     $row = $this->model->get($id);
        //     $row['freight_status'] = "1";
        //     $row['orderstate'] = 2;
        //     $row['freight_time'] = time();
        //     $row['express_company'] = input('post.express_company');
        //     $row['express_no'] = input('post.express_no');
        //     $row->save();
        //     $this->success();
        // }
        if($this->request->isPost())
        {
            $id = input('post.ids');
            $row = $this->model->get($id);
            $params = $this->request->post('row/a');
            $row['peisong_user_id'] = $params['peisong_user_id'];
            $row['orderstate'] = 1;
            $row->save();
            $this->success();
        }
        $param = $this->request->param();
        // $row = $this->model->get($ids);
        $row = $this->model->with(['peisong','mendian'])->find($ids);
        // var_dump($row->toArray()['peisong']);
        $this->view->assign('vo', $row);
        $this->view->assign('peisong', $row->toArray()['peisong']);

        $map['order_id'] = $ids;
        $peisong_desc = Db::table('fa_pifa_orderdesc')->where($map)->select();


        foreach ($peisong_desc as $key => $value) {
           $value['images'] = explode(',',$value['images']);

           foreach ($value['images'] as $key1 => $value1) {
               $value['images'][$key1] = $value1;
           }

           $peisong_desc[$key]['images'] = $value['images'];

           
           $peisong_desc[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
        }


        
        $this->view->assign('peisong_desc', $peisong_desc);

        return $this->view->fetch();
    }

    //同意退款(退货)
    public function refund($ids = null)
    {   


        if($this->request->isPost())
        {
            
            $post = $this->request->post('row/a');
            $res = $this->model->find($ids);


            if (empty($res)) {
               $this->error("订单不存在");
            }

            if ($res['sh_status'] != 1) {
                $this->error("订单已处理");
            }

            if ($post['sh_status'] == 2) {

                if ($res['pay_type'] == 0) {
                    $config = Service::getConfig('wechat');
                    $order_sn = $res['transactionid'];
                    try {

                         $response = Pay::wechat($config)->refund([
                                '_action'          => 'mini',
                                'transaction_id'  => $res['transactionid'],
                                'out_refund_no' => 'RE'.time(),
                                'amount' => [
                                    'refund' => $post['price']*100,
                                    'total' => $res['price']*100,
                                    'currency' => 'CNY',
                                ],
                        ]);



            
                      
                        if (!$response['result_code'] || $response['result_code'] != 'SUCCESS') {
                            throw new \Exception(($response['err_code'] ?? '') . ':' . ($response['err_code_des'] ?? '未知退款错误'));
                        }else{

                            $res->sh_status = 2;
                            $res->orderstate = 4;
                            $res->shippingstate = 3;
                            $res->tui_price = $post['price'];
                            $res->re_price = bcadd($post['price'],$res->re_price,2);
                            $res->save();

                        }
                    } catch (\Exception $e) {
                        Log::write("[shop][refund][{$order_sn}]同步退款失败，失败原因：" . $e->getMessage(), 'refund');
                       

                        $this->error("同步退款失败，失败原因：" . $e->getMessage());
                    }
                }else{
                    $notifyurl = 'http://yuanmushop.xinanqy.com/api/refund/index';


                    $map2['wx_order'] = $res['transactionid'];

                    $order_liushu = Db::table('fa_pifa_orderliushui')->where($map2)->find();


                    $res = Huipay::Tuikuan($order_liushu['order_no'],$res['price'],$post['price'],$notifyurl);
                    if (!$res['success']) {
                        $this->error("请求退款失败,具体原因".$res['errorMsg']);
                    }
                    
                    
                    $res['result'] = json_decode($res['result'],true);
                    
                     if ($res['result']['orderStatus'] != 'PROCESSING') {
                        $this->error("请求退款失败,具体原因".$res['result']['respMsg']);
                    }
                    
                   
                    $map4['id'] = $ids;

                    $updata['sh_status'] = 2;
                    $updata['orderstate'] = 4;
                    
                    $updata['shippingstate'] = 3;
                    $updata['re_price'] = bcadd($post['price'],$res->re_price,2);

                    Db::table('fa_pifa_order')->where($map4)->update($updata);

                }
                
            }else{
                $res->sh_status = $post['sh_status'];
                $res->save();
            }

            $this->success("成功");
        
        }

        $row = $this->model->find($ids);

        if ($row['sh_status'] != 1) {
            $this->error("订单已处理");
        }

        $Orderitem = new \app\admin\model\pifa\Orderitem;

        $map2['order_id'] = $ids;
        $map2['sh_status'] = 0;
        $order_item = $Orderitem->with('goods')->where($map2)->select();


        $price = 0;

        foreach ($order_item as $key => $value) {
            $price = bcadd($price, $value['price'],2);
           $order_item[$key]['goods']['image'] = cdnurl($value['goods']['image']);
        }
        $this->view->assign('order_item', $order_item);
        $this->view->assign('price', $price);

        $row['price'] = bcsub($row['price'], $row['re_price'],2);

        $this->view->assign('row', $row);
        return $this->view->fetch();
      
    }



     //同意退款(退货)
    public function refund2($ids = null)
    {   


        if($this->request->isPost())
        {
            
            $post = $this->request->post('row/a');
            $res = $this->model->find($ids);


            if (empty($res)) {
               $this->error("订单不存在");
            }

            if ($post['sh_status'] == 2) {
                if ($res['pay_type'] == 0) {
                    $config = Service::getConfig('wechat');
                    $order_sn = $res['transactionid'];
                    try {

                        $res_data = [
                                '_action'          => 'mini',
                                'transaction_id'  => $res['transactionid'],
                                'out_refund_no' => 'RE'.time(),
                                'amount' => [
                                    'refund' => $post['price']*100,
                                    'total' => $res['price']*100,
                                    'currency' => 'CNY',
                                ],
                        ];
                       
                        $response = Pay::wechat($config)->refund($res_data);
                         

                      
                        if (isset($response['status']) && $response['status'] === 'SUCCESS') {
                            $res->tui_price = $post['price'];
                            $res->re_price = bcadd($post['price'],$res->re_price,2);
                            if ($res->re_price == $res['price']) {
                                $res->sh_status = 2;
                                $res->orderstate = 4;
                                $res->shippingstate = 1;
                            }
                            $res->save();
                        } elseif ($response['status'] === 'PROCESSING') {
                            $res->tui_price = $post['price'];
                            $res->re_price = bcadd($post['price'],$res->re_price,2);
                            if ($res->re_price == $res['price']) {
                                $res->sh_status = 2;
                                $res->orderstate = 4;
                                $res->shippingstate = 1;
                            }
                            $res->save();
                        } else {
                             throw new \Exception(($response['items']['message'] ?? '') . ':' . ($response['message'] ?? '未知退款错误'));
                        }
                        
                    } catch (\Exception $e) {
                        Log::write("[shop][refund][{$order_sn}]同步退款失败，失败原因：" . $e->getMessage(), 'refund');
                       

                        $this->error("同步退款失败，失败原因：" . $e->getMessage());
                    }
                }else{
                    $notifyurl = 'http://yuanmushop.xinanqy.com/api/refund/index';


                    $map2['wx_order'] = $res['transactionid'];

                    $order_liushu = Db::table('fa_pifa_orderliushui')->where($map2)->find();


                    $res = Huipay::Tuikuan($order_liushu['order_no'],$res['price'],$post['price'],$notifyurl);
                    if (!$res['success']) {
                        $this->error("请求退款失败,具体原因".$res['errorMsg']);
                    }
                    
                    
                    $res['result'] = json_decode($res['result'],true);
                    
                     if ($res['result']['orderStatus'] != 'PROCESSING') {
                        $this->error("请求退款失败,具体原因".$res['result']['respMsg']);
                    }
                    
                    $map4['id'] = $ids;
                    $updata['re_price'] = bcadd($post['price'],$res->re_price,2);
                    Db::table('fa_pifa_order')->where($map4)->update($updata);

                }
                
            }

            $this->success("成功");
        
        }

        $row = $this->model->find($ids);


        $Orderitem = new \app\admin\model\pifa\Orderitem;

        $map3['order_id'] = $ids;
        $map3['sh_status'] = 0;
        $order_item = $Orderitem->with('goods')->where($map3)->select();


        $price = 0;

        foreach ($order_item as $key => $value) {
            $price = bcadd($price, $value['price'],2);
           $order_item[$key]['goods']['image'] = cdnurl($value['goods']['image']);
        }
        $this->view->assign('order_item', $order_item);
        $this->view->assign('price', $price);
        $row['price'] = bcsub($row['price'], $row['re_price'],2);
        $this->view->assign('row', $row);
        return $this->view->fetch();
      
    }




    
    //同意退款(退货)
    public function daying()
    {   



         if($this->request->isPost())
        {   

            $param = $this->request->param();
            
            if (empty($param['order_id'])) {
                $this->error('请选择商品');
            }
            $ids = explode(',',$param['order_id']);
            foreach ($ids as $key => $value) {
                QueueApi::push('addons\faqueue\library\jobs\OrderDaying',$value,'dongping');
            }
            $insdata['order_ids'] = implode(',',$ids);
            $insdata['createtime'] = date('Y-m-d H:i:s');
        
            $this->success();
        }

        $param = $this->request->param();

        $this->view->assign("ids", $param['ids']);
        return $this->view->fetch();



      
    }



    //同意退款(退货)
    public function chengben()
    {   

        $param = $this->request->param();

        $ids = explode(',',$param['ids']);

        $Orderitem = new \app\admin\model\pifa\Orderitem;
        $map['order_id'] = ['in',$ids];
        $order = $Orderitem->with('goods')->where($map)->field('sum(goods_num) as goods_num,sum(goods_price4) as goods_price4,sum(price) as price')->group('goods_item_id')->select();


        $chenben = 0;
        $xiaoshou = 0;

        $map2['pid'] = 0;
        $fenlei = Db::table('fa_litestore_category')->cache(true)->column('name','id');



        foreach ($order as $key => $value) {
           

            $order[$key]['category'] = '未知';


            if (!empty($value['goods']['category_id'])) {
                $category_id = explode(',',$value['goods']['category_id']);
                $category_id2 = $category_id[0];

                if (isset($fenlei[$category_id2])) {
                   $order[$key]['category'] = $fenlei[$category_id2];
                }
            }


            $chenben = bcadd($chenben, $value['goods_price4'],2);
            $xiaoshou = bcadd($xiaoshou, $value['price'],2);
        }
        $result['list'] = $order;
        $result['chenben'] = $chenben;
        $result['xiaoshou'] = $xiaoshou;
        
        $this->view->assign("order", $result);
        return $this->view->fetch();



      
    }



}
